
const lib_configurg={
    loading_time_out:15000,//15秒 loading等待时间，超过此时间将自动取消loading
}
/********异步提交函数**************************/
//form支持多表单提交，中间用,隔开，url为提交地址
function subForm(form, url) {

    //防止高频点击
    var date = new Date();
    var time = date.getTime(); //毫秒时间戳
    let finger = 2;
    if (typeof minTime == "undefined") {
        minTime = time + 2000; //下次点击的最小时间
    } else {
        if (minTime && time < minTime) {
            finger = 1;
            warn("操作过于频繁");
            console.log("time:" + time + "，mintime:" + minTime + "，差额：" + (time - minTime));
        } else {
            finger = 2;
            minTime = time + 2000; //下次点击的最小时间
        }
    }

    if (finger === 2) {
        let con = setTimeout(function (){
            $("#loading", parent.document).hide();
        },lib_configurg.loading_time_out);
        $("#loading", parent.document).show();
        //串联表单
        var formName = form.split(",");
        var serialize = "";
        var a = "";
        for (var i = 0; i < formName.length; i++) {
            if (serialize === "") {
                a = "";
            } else {
                a = "&";
            }
            if (formName[i] !== "") {
                serialize += a + $("[name=" + formName[i] + "]").serialize();
            }
        }
        //异步提交数据
        $.post(url, serialize, function (data) {
            //console.log(data);
            if (data.warn === 2 || data.warn === '2') {
                if(data.href){
                    //如果异步返回的json参数中定义了重定向url，则跳转到本url
                    window.location.href = data.href;
                }else if($("#renovate").attr("url")){
                    //页卡切换时会保存菜单关键字在renovate的url中
                    window.location.href = $("#renovate").attr("url");
                }else{
                    window.location.reload();
                }
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", parent.document).hide();
            clearTimeout(con);
        }, "json");
    }
}

/******************警示弹出层*****************/
function warn(warn, type = 'info') {
    msg(warn, type);
    // $("#warn").show();
    // $("#warnWord").html(warn);
}

/*根据省份选择城市*/
function regionProvince(obj) {
    //参数准备
    var formName = $(obj).parents("form").attr("name");
    var provinceValue = $(obj).val();
    var city = $(obj).next("select");
    var area = $(city).next("select");
    //异步获取城市
    $.post(root + "library/libData?type=getCity", {
        province: provinceValue
    }, function (data) {
        city.html(data.city);
    }, "json");
    //初始化区域
    area.html("<option value=''>--区域--</option>");
}

/*根据城市选择区域*/
function regionCity(obj) {
    //参数准备
    var formName = $(obj).parents("form").attr("name");
    var provinceValue = $(obj).prev("select").val();
    var cityValue = $(obj).val();
    var area = $(obj).next("select");
    //异步获取区域
    $.post(root + "library/libData?type=getArea", {
        province: provinceValue,
        city: cityValue
    }, function (data) {
        area.html(data.area);
    }, "json");
}

/*******获取本地路径*****************/
//sourceId：文件域ID号
function getFileUrl(sourceId) {
    var url;
    if (navigator.userAgent.indexOf("MSIE") >= 1) { // IE
        url = document.getElementById(sourceId).value;
    } else if (navigator.userAgent.indexOf("Firefox") > 0) { // Firefox
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else if (navigator.userAgent.indexOf("Chrome") > 0) { // Chrome
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    } else {
        url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
    }
    return url;
}

/*******获取短信验证码*****************/
function newProve(tel) {
    $.post(root + "library/libData?type=newProve", {
        tel: tel
    }, function (data) {
        warn(data.warn);
    }, "json");
}

/*******跳转*****************/
function href(url) {
    window.location.href = url.includes(root) ? url : root + url;
    return false;
}

/*弹出层移动函数*/
function move(id) {
    //参数初始化
    var win = $("#" + id).children(".win"); //需要移动的弹出层窗口
    var title = $("#" + id).find(".winTitle"); //点击区域
    //鼠标按下
    title.mousedown(function (e) {
        var ev = e || event;
        var startX = ev.clientX;
        var startY = ev.clientY;
        var left = parseInt(win.css("margin-left"));
        var top = parseInt(win.css("margin-top"));
        document.onmousemove = function (m) {
            var mv = m || event;
            var endX = mv.clientX;
            var endY = mv.clientY;
            var moveX = endX - startX;
            var moveY = endY - startY;
            //计算值
            winLeft = (left + moveX) + "px";
            winTop = (top + moveY) + "px";
            //移动弹窗
            win.css({
                "margin-top": winTop,
                "margin-left": winLeft
            });
        }
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    })
};
(function ($) {
    var val = '关键字';
    $.fn.fSelect = function (options) {
        var settings = '';
        if (typeof options == 'string') {
            settings = options;
        } else {
            settings = $.extend({
                placeholder: '关键字',
                numDisplayed: 15,
                overflowText: '{n} selected',
                searchText: '关键字',
                showSearch: true
            }, options);
        }

        /**
         * Constructor
         */
        function fSelect(select, settings) {
            this.$select = $(select);
            this.settings = settings;
            this.create();
        }

        /**
         * Prototype class
         */
        fSelect.prototype = {
            create: function () {
                var multiple = this.$select.is('[multiple]') ? ' multiple' : '';
                var addStyle = this.settings.class ? ' ' + this.settings.class : '';
                this.$select.wrap('<div class="fs-wrap' + multiple + addStyle + '"></div>');
                val = this.$select.attr('title');
                this.$select.before('<div class="fs-label-wrap"><div class="fs-label">' + val + '</div><span class="fs-arrow"></span></div>');
                this.$select.before('<div class="fs-dropdown hidden"><div class="fs-options"></div></div>');
                this.$select.addClass('hidden');
                this.$wrap = this.$select.closest('.fs-wrap');
                //设置跟父级元素fs-wrap一样的宽度
                this.$select.parent().find(".fs-dropdown").width(this.$select.parent().outerWidth());
                this.reload();
            },
            reload: function () {
                if (this.settings.showSearch) {
                    var search = '<div class="fs-search"><input type="search" placeholder="' + this.settings.searchText + '" /></div>';
                    this.$wrap.find('.fs-dropdown').prepend(search);
                }
                var choices = this.buildOptions(this.$select);
                this.$wrap.find('.fs-options').html(choices);
                this.reloadDropdownLabel('reload');
            },
            destroy: function () {
                this.$wrap.find('.fs-label-wrap').remove();
                this.$wrap.find('.fs-dropdown').remove();
                this.$select.unwrap().removeClass('hidden');
            },
            buildOptions: function ($element) {
                var $this = this;
                var choices = '';
                $element.children().each(function (i, el) {
                    var $el = $(el);
                    if ('optgroup' == $el.prop('nodeName').toLowerCase()) {
                        choices += '<div class="fs-optgroup">';
                        choices += '<div class="fs-optgroup-label">' + $el.prop('label') + '</div>';
                        choices += $this.buildOptions($el);
                        choices += '</div>';
                    } else {
                        var selected = $el.is('[selected]') ? ' selected' : '';
                        if (!$el.prop('value') && $el.html().indexOf("-") !== -1) {
                            choices += '<div class="fs-option fs-option-no ' + selected + '" data-value=""><div title="' + $el.html() + '" class="fs-option-label">' + $el.html() + '</div></div>';
                        } else {
                            choices += '<div class="fs-option' + selected + '" data-value="' + $el.prop('value') + '"><span class="fs-checkbox"><i></i></span><div title="' + $el.html() + '" class="fs-option-label">' + $el.html() + '</div></div>';
                        }
                    }
                });
                return choices;
            },
            reloadDropdownLabel: function (source='') {
                var settings = this.settings;
                var labelText = [];
                this.$wrap.find('.fs-option.selected').each(function (i, el) {
                    labelText.push($(el).find('.fs-option-label').text());
                });
                if (labelText.length < 1) {
                    //labelText = settings.placeholder;
                    labelText = val;
                } else if (labelText.length > settings.numDisplayed) {
                    labelText = settings.overflowText.replace('{n}', labelText.length);
                } else {
                    labelText = labelText.join(', ');
                }
                this.$wrap.find('.fs-label').html(labelText);
                if(source!=='reload'){
                    this.$select.change();
                }
            }
        }
        /**
         * Loop through each matching element
         */
        return this.each(function () {
            var data = $(this).data('fSelect');
            if (!data) {
                data = new fSelect(this, settings);
                $(this).data('fSelect', data);
            }
            if (typeof settings == 'string') {
                data[settings]();
            }
        });
    }
    /**
     * Events
     */
    window.fSelect = {
        'active': null,
        'idx': -1
    };

    function setIndexes($wrap) {
        $wrap.find('.fs-option:not(.hidden)').each(function (i, el) {
            $(el).attr('data-index', i);
            $wrap.find('.fs-option').removeClass('hl');
        });
        $wrap.find('.fs-search input').focus();
        window.fSelect.idx = -1;
    }

    function setScroll($wrap) {
        var $container = $wrap.find('.fs-options');
        var $selected = $wrap.find('.fs-option.hl');
        var itemMin = $selected.offset().top + $container.scrollTop();
        var itemMax = itemMin + $selected.outerHeight();
        var containerMin = $container.offset().top + $container.scrollTop();
        var containerMax = containerMin + $container.outerHeight();
        if (itemMax > containerMax) { // scroll down
            var to = $container.scrollTop() + itemMax - containerMax;
            $container.scrollTop(to);
        } else if (itemMin < containerMin) { // scroll up
            var to = $container.scrollTop() - containerMin - itemMin;
            $container.scrollTop(to);
        }
    }

    $(document).on('click', '.fs-option', function () {
        var $wrap = $(this).closest('.fs-wrap');
        if ($wrap.hasClass('multiple')) {
            var selected = [];
            $(this).toggleClass('selected');
            $wrap.find('.fs-option.selected').each(function (i, el) {
                selected.push($(el).attr('data-value'));
            });
        } else {
            var selected = $(this).attr('data-value');
            $wrap.find('.fs-option').removeClass('selected');
            $(this).addClass('selected');
            $wrap.find('.fs-dropdown').addClass('hidden');
        }
        $wrap.find('select').val(selected);
        $wrap.find('select').fSelect('reloadDropdownLabel');
    });
    $(document).on('keyup', '.fs-search input', function (e) {
        if (40 == e.which) {
            $(this).blur();
            return;
        }
        var $wrap = $(this).closest('.fs-wrap');
        var keywords = $(this).val();
        var ret = /^[a-zA-Z]+$/;
        $wrap.find('.fs-option, .fs-optgroup-label').removeClass('hidden');
        if ('' != keywords) {
            $wrap.find('.fs-option').each(function () {
                var regex = new RegExp(keywords, 'gi');
                if (ret.test(keywords)) {
                    if (null === ($(this).find('.fs-option-label').text()).match(regex)) {
                        $(this).addClass('hidden');
                    }
                } else {
                    if (null === $(this).find('.fs-option-label').text().match(regex)) {
                        $(this).addClass('hidden');
                    }
                }
            });
            $wrap.find('.fs-optgroup-label').each(function () {
                var num_visible = $(this).closest('.fs-optgroup').find('.fs-option:not(.hidden)').length;
                if (num_visible < 1) {
                    $(this).addClass('hidden');
                }
            });
        }
        setIndexes($wrap);
    });
    $(document).on('click', function (e) {
        var $el = $(e.target);
        var $wrap = $el.closest('.fs-wrap');
        if (0 < $wrap.length) {
            if ($el.hasClass('fs-label')) {
                window.fSelect.active = $wrap;
                var is_hidden = $wrap.find('.fs-dropdown').hasClass('hidden');
                $('.fs-dropdown').addClass('hidden');
                if (is_hidden) {
                    $wrap.find('.fs-dropdown').removeClass('hidden');
                    let h = $wrap.height()+7;
                    let offset = $wrap.offset();
                    $wrap.find(".fs-dropdown").offset({"top": offset.top+h, "left": offset.left});
                } else {
                    $wrap.find('.fs-dropdown').addClass('hidden');
                }
                setIndexes($wrap);
            }
        } else {
            $('.fs-dropdown').addClass('hidden');
            window.fSelect.active = null;
        }
    });
    $(document).on('keydown', function (e) {
        var $wrap = window.fSelect.active;
        if (null === $wrap) {
            return;
        } else if (38 == e.which) { // up
            e.preventDefault();
            $wrap.find('.fs-option').removeClass('hl');
            if (window.fSelect.idx > 0) {
                window.fSelect.idx--;
                $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
                setScroll($wrap);
            } else {
                window.fSelect.idx = -1;
                $wrap.find('.fs-search input').focus();
            }
        } else if (40 == e.which) { // down
            e.preventDefault();
            var last_index = $wrap.find('.fs-option:last').attr('data-index');
            if (window.fSelect.idx < parseInt(last_index)) {
                window.fSelect.idx++;
                $wrap.find('.fs-option').removeClass('hl');
                $wrap.find('.fs-option[data-index=' + window.fSelect.idx + ']').addClass('hl');
                setScroll($wrap);
            }
        } else if (32 == e.which || 13 == e.which) { // space, enter
            $wrap.find('.fs-option.hl').click();
        } else if (27 == e.which) { // esc
            $('.fs-dropdown').addClass('hidden');
            window.fSelect.active = null;
        }
    });
})(jQuery);


// 提示框
(function () {
    "use strict";
    $.Toast = function (message, type, options) {
        let defaultOptions = {
            appendTo: "body",
            stack: false, // 堆叠显示
            positionClass: "toast-bottom-right",
            fullscreen: false,
            width: 250,
            spacing: 20,
            timeout: 4000,
            progress: false,
        }
        let $options = $.extend(true, {}, defaultOptions, options);
        let spacing = $options.spacing;
        let css = {
            "position": ($options.appendTo === "body") ? "fixed" : "absolute",
            "width": $options.width,
            "display": "none",
            "border-radius": '5px',
            "z-index": 99999
        }
        let ele = $(`<div class="toast-item-wrapper ${type} ${$options.positionClass}"></div>`);
        $(`<p class="toast-message">${message}</p>`).appendTo(ele);

        if ($options.fullscreen) {
            ele.addClass("fullscreen");
        }
        if ($options.progress && $options.timeout > 0) {
            $(`<div class="toast-progress"></div>`).appendTo(ele);
        }
        if ($options.stack) {
            if ($options.positionClass.indexOf("toast-top") !== -1) {
                $($options.appendTo).find('.toast-item-wrapper').each(function () {
                    css["top"] = parseInt($(this).css("top")) + this.offsetHeight + spacing;
                });
            } else if ($options.positionClass.indexOf("toast-bottom") !== -1) {
                $($options.appendTo).find('.toast-item-wrapper').each(function () {
                    css["bottom"] = parseInt($(this).css("bottom")) + this.offsetHeight + spacing;
                });
            }
        }
        ele.css(css);
        ele.appendTo($options.appendTo);
        if (ele.fadeIn) {
            ele.fadeIn();
        } else {
            $alert.css({
                display: 'block',
                opacity: 1
            });
        }

        function removeToast() {
            $.Toast.remove(ele);
        }

        if ($options.timeout > 0) {
            setTimeout(removeToast, $options.timeout);
            if ($options.progress) {
                $(".toast-progress", ele).animate({
                    "width": "100%"
                }, $options.timeout);
            }
        }
        return ele;
    }
    $.Toast.remove = function (ele) {
        if (ele.fadeOut) {
            ele.fadeOut(function () {
                return ele.remove();
            });
        } else {
            ele.remove();
        }
    }
})();


/**
 *
 * @param text 消息
 * @param type 类型 支持 info, success, error
 * @returns {*|jQuery|HTMLElement}
 */
function msg(text, type = 'info') {
    return $.Toast(text, type, {
        fullscreen: false,
        timeout: 2000,
        progress: true,
    });
}